package com.gsk.europepharma.salesReport.struts.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Query;
import org.hibernate.Session;

import com.gsk.europepharma.salesReport.hibernate.dao.tbSpBoSRSectoDAO;

/**
 * Gestion des donnees pour l'affichage du tableau contenant le top UGPN ou la liste des medecins.
 */
public class DataGrid extends Action {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		// Variables de session
		HttpSession sessionObject = request.getSession();
		Integer cs_adm_pdt = (Integer) sessionObject.getAttribute("cs_adm_pdt");
		Integer cs_adm_rgpt = (Integer) sessionObject.getAttribute("cs_adm_rgpt");
		Integer cs_adm_prstn = (Integer) sessionObject.getAttribute("cs_adm_prstn");
		Integer cs_network = (Integer) sessionObject.getAttribute("cs_network");
		// Integer cs_month = (Integer) sessionObject.getAttribute("cs_month");
		// Fin de session
		
		String idGeog = request.getParameter("idGeog");
		Integer idGeogInteger = Integer.parseInt(idGeog);
		String nivGeog = request.getParameter("nivGeog");
		
		String source = request.getParameter("source");
		Integer CS_SRC = Integer.parseInt(source);
		String unite = request.getParameter("unite");
		String periode = request.getParameter("periode");
		
		String codeUgp = request.getParameter("codeUgp");
		
		JSONArray jsonArrayLines = new JSONArray();
		
		if (codeUgp != null && !codeUgp.equals("")) { // ACTION : affichage des medecins 
			
			String cs_division_string = request.getParameter("cs_division");
			Integer cs_division = Integer.parseInt(cs_division_string);
			String periodeActivite = request.getParameter("periodeActivite");
			String specialite = request.getParameter("specialite");
			String segments = request.getParameter("segments");
			
			tbSpBoSRSectoDAO salesDAO = new tbSpBoSRSectoDAO();
			Session session = salesDAO.getSession();
						
			Query req = null;
			
			String strReq = salesDAO.QUERY_QUERY_LISTE_CONTACT_UGP;
			
			req = session.getNamedQuery(strReq); 
			req.setString("ugp", codeUgp);
			ArrayList result = new ArrayList(req.list());
			Iterator iter = result.iterator();
			
			int i = 0;
			
			while (iter.hasNext()) {
				Object[] val = (Object[]) iter.next();
				
				JSONObject jsonObjectLine = new JSONObject();
				jsonObjectLine.put("id", i);
				i++;
				jsonObjectLine.put("name", val[4].toString());
				jsonObjectLine.put("firstname", val[5].toString());
				jsonObjectLine.put("zipCode", val[7].toString());
				jsonObjectLine.put("city", val[8].toString());
				jsonObjectLine.put("spe", val[9].toString());
				
				if (i % 2 == 0) {
					jsonObjectLine.put("cible", "B"); // TODO:
				} else {
					jsonObjectLine.put("cible", "A"); // TODO:
				}
				jsonObjectLine.put("nbCalls", i + " / " + i); // TODO:
				jsonObjectLine.put("dernVis", "02/10/" + i); // TODO:
				jsonObjectLine.put("proVis", "01/01/" + i); // TODO:
				
				jsonArrayLines.add(jsonObjectLine);
			}
			
		} else { // ACTION : affichage du top ten UGPN
			
			// Nombre UGPN par page 
			String nombreUGPNParPageString = request.getParameter("itemsParPage");
			int nombreUGPNParPage = Integer.parseInt(nombreUGPNParPageString);
			// Indice de debut 
			String start = request.getParameter("start");
			
			int nombreTotalUGPN = 0;
			// Requete pour determiner le nombre total UGPN 
			tbSpBoSRSectoDAO salesDAO = new tbSpBoSRSectoDAO();
			Session session = salesDAO.getSession();
			Query req = null;
			String strReq = "";
			if (request.getParameter("filter") != null) {
				strReq = salesDAO.QUERY_TOP_UGP_COUNT_WITH_FILTER; 
			} else {
				strReq = salesDAO.QUERY_TOP_UGP_COUNT_WITHOUT_FILTER;
			}
			req = session.getNamedQuery(strReq);
			req.setInteger("cs_adm_pdt", cs_adm_pdt);
			req.setInteger("cs_adm_rgpt", cs_adm_rgpt);
			req.setInteger("cs_adm_prstn", cs_adm_prstn);
			req.setInteger("CS_SRC", CS_SRC);
			req.setInteger("cs_network", cs_network);
			req.setString("nivGeog", nivGeog);
			req.setInteger("idGeog", idGeogInteger); 
			if (request.getParameter("filter") != null) {
				String tab[] = request.getParameter("filter").split("\"");
				String value = tab[7];
				String property = tab[11];
				req.setString("fieldFilterUgpn", property);
				req.setString("valueFilterUgpn", value.toUpperCase());
			} else {
				//req.setString("fieldFilterUgpn", "nofilter");
				//req.setString("valueFilterUgpn", "AAAAAA");
			}
			
			ArrayList result = new ArrayList(req.list());
			nombreTotalUGPN = Integer.parseInt(result.get(0).toString());
			
			// Mise en session du nombre UGPN
			sessionObject.setAttribute("nombreUGPN", result.get(0).toString());
			
			// Calcul des indices min et max 
			int beginIndex = Integer.parseInt(start);
			int endIndex = Integer.parseInt(start) + nombreUGPNParPage;
			if (endIndex > nombreTotalUGPN) {
				endIndex = nombreTotalUGPN;
			}
			
			// Requete
			salesDAO = new tbSpBoSRSectoDAO();
			session = salesDAO.getSession();
			req = null;
			strReq = "";
			if (request.getParameter("filter") != null) {
				strReq = salesDAO.QUERY_TOP_UGP_WITH_FILTER;
			} else {
				strReq = salesDAO.QUERY_TOP_UGP_WITHOUT_FILTER;
			}
			req = session.createSQLQuery(session.getNamedQuery(strReq).getQueryString());
			req.setParameter("data1",		unite + "CC");
			req.setParameter("data2",		unite + "MM");
			req.setInteger("cs_adm_pdt",	cs_adm_pdt);
			req.setInteger("cs_adm_rgpt",	cs_adm_rgpt);
			req.setInteger("cs_adm_prstn",	cs_adm_prstn);
			req.setInteger("CS_SRC",		CS_SRC);
			req.setInteger("cs_network",	cs_network);
			req.setString("nivGeog",		nivGeog);
			req.setInteger("idGeog",		idGeogInteger); 
			req.setInteger("min",			beginIndex);
			req.setInteger("max",			endIndex);
			if (request.getParameter("sort") != null) {
				String tab[] = request.getParameter("sort").split("\"");
				String property = tab[3];
				String order = tab[7];
				req.setString("fieldOrder", property);
				req.setString("ascDescOrder", order);
			} else {
				req.setString("fieldOrder", "noorder");
				req.setString("ascDescOrder", "ASC");
			}
			
			if (request.getParameter("filter") != null) {
				String tab[] = request.getParameter("filter").split("\"");
				String value = tab[7];
				String property = tab[11];
				req.setString("fieldFilterUgpn", property);
				req.setString("valueFilterUgpn", value);
			} else {
				//req.setString("fieldFilterUgpn", "nofilter");
				//req.setString("valueFilterUgpn", "");
			}
			
			result = new ArrayList(req.list());
			//result = new ArrayList();
			
			Iterator iter = result.iterator();
			
			int i = 1;
			
			jsonArrayLines = new JSONArray();
			JSONObject jsonObjectLine = new JSONObject();
			
			while (iter.hasNext()) {
				Object[] val = (Object[]) iter.next();
		           
				jsonObjectLine = new JSONObject();
				jsonObjectLine.put("id", i);
				i++;
				jsonObjectLine.put("codeUgp", val[0].toString());
				jsonObjectLine.put("ugpn", val[1].toString());
				if (val[2] != null) {
					jsonObjectLine.put("pmCm3", Double.parseDouble(val[2].toString()));
				} else {
					jsonObjectLine.put("pmCm3", "");
				}
				if (val[3] != null) {
					jsonObjectLine.put("pmCm3Delta", Double.parseDouble(val[3].toString()));
				} else {
					jsonObjectLine.put("pmCm3Delta", "");
				}
				if (val[4] != null) {
					jsonObjectLine.put("pm", Double.parseDouble(val[4].toString()));
				} else {
					jsonObjectLine.put("pm", "");
				}
				if (val[5] != null) {
					jsonObjectLine.put("pmDelta", Double.parseDouble(val[5].toString()));
				} else {
					jsonObjectLine.put("pmDelta", "");
				}
				jsonArrayLines.add(jsonObjectLine);
			}
			
			HashMap hm = new HashMap();
			JSONObject res = new JSONObject();
			res.put("total",	nombreTotalUGPN);
			res.put("data",		jsonArrayLines);
			res.put("id",		"gridUGPNStore");
			hm.put("result",	res);
			
			JSONObject json = JSONObject.fromObject(hm);
			response.addHeader("Content-Type", "application/json");
	        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
	        // response.getOutputStream().flush();
			
			return null;
			
		}
		
		HashMap hm = new HashMap();
		hm.put("lines", jsonArrayLines);
		
		JSONObject json = JSONObject.fromObject(hm);
		response.addHeader("Content-Type", "application/json");
        response.getOutputStream().write(json.toString().getBytes("UTF-8"));
        response.getOutputStream().flush();
		
		return null;
	}
	
}
